<template>
  <div class="customer-detail" v-loading="loading">
    <template v-if="customer">
      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="客户编码">{{ customer.customerCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ customer.customerName }}</el-descriptions-item>
        <el-descriptions-item label="客户简称">{{ customer.shortName }}</el-descriptions-item>
        <el-descriptions-item label="客户类型">{{ getCustomerTypeName(customer.customerType) }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{ customer.responsiblePerson }}</el-descriptions-item>
        <el-descriptions-item label="负责人电话">{{ customer.responsiblePhone }}</el-descriptions-item>
        <el-descriptions-item label="负责人邮箱">{{ customer.responsibleEmail }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">
          <el-tag :type="getStatusType(customer.status)">
            {{ getStatusText(customer.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ customer.address }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ customer.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(customer.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(customer.updateTime) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 联系人信息 -->
      <div class="section-title">
        <h3>联系人信息</h3>
      </div>

      <el-table :data="customer.contacts" style="width: 100%" border>
        <el-table-column prop="contactName" label="联系人姓名" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getContactStatusType(row.status)">
              {{ getContactStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 相关项目 -->
      <div class="section-title">
        <h3>相关项目</h3>
      </div>

      <el-empty v-if="!relatedProjects.length" description="暂无相关项目" />
      <el-table v-else :data="relatedProjects" style="width: 100%" border>
        <el-table-column prop="projectCode" label="项目编码" width="120" />
        <el-table-column prop="projectName" label="项目名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="responsiblePerson" label="负责人" width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getProjectStatusType(row.status)">
              {{ getProjectStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 相关工单 -->
      <div class="section-title">
        <h3>相关工单</h3>
      </div>

      <el-empty v-if="!relatedTickets.length" description="暂无相关工单" />
      <el-table v-else :data="relatedTickets" style="width: 100%" border>
        <el-table-column prop="ticketNo" label="工单编号" width="180" />
        <el-table-column prop="title" label="工单标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ticketType" label="工单类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.ticketType === 'Bug' ? 'danger' : 'success'">
              {{ row.ticketType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getTicketStatusType(row.status)">
              {{ getTicketStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getTicketPriorityType(row.priority)">
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-empty v-else description="未找到客户信息" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useCustomerStore } from '@/store/customer'
import type { Customer } from '@/store/customer'
import customerApi from '@/api/customer'

// 定义props
const props = defineProps<{
  customerId?: string;
}>()

// 存储
const customerStore = useCustomerStore()

// 状态
const loading = ref(false)
const customer = ref<Customer | null>(null)
const customerTypes = ref<{ code: string; name: string }[]>([])
const relatedProjects = ref<any[]>([])
const relatedTickets = ref<any[]>([])

// 获取客户类型名称
const getCustomerTypeName = (code: string) => {
  const type = customerTypes.value.find(t => t.code === code)
  return type?.name || code
}

// 获取客户状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pre-sales': '售前',
    'normal': '正常',
    'deleted': '注销'
  }
  return statusMap[status] || status
}

// 获取客户状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pre-sales': 'warning',
    'normal': 'success',
    'deleted': 'danger'
  }
  return typeMap[status] || ''
}

// 获取联系人状态文本
const getContactStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'normal': '正常',
    'disabled': '禁用',
    'deleted': '注销'
  }
  return statusMap[status] || status
}

// 获取联系人状态类型
const getContactStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'normal': 'success',
    'disabled': 'warning',
    'deleted': 'danger'
  }
  return typeMap[status] || ''
}

// 获取项目状态文本
const getProjectStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'pre-sales': '售前',
    'not-started': '未开始',
    'in-progress': '进行中',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

// 获取项目状态类型
const getProjectStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pre-sales': 'info',
    'not-started': 'warning',
    'in-progress': 'primary',
    'completed': 'success'
  }
  return typeMap[status] || ''
}

// 获取工单状态文本
const getTicketStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'draft': '草稿',
    'submitted': '提交',
    'confirmed': '需求确认',
    'verified': '验证通过',
    'pending': '待处理',
    'processing': '处理中',
    'closed': '已关闭'
  }
  return statusMap[status] || status
}

// 获取工单状态类型
const getTicketStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'draft': 'info',
    'submitted': 'warning',
    'confirmed': 'primary',
    'verified': 'success',
    'pending': 'warning',
    'processing': 'primary',
    'closed': 'success'
  }
  return typeMap[status] || ''
}

// 获取工单优先级类型
const getTicketPriorityType = (priority: string) => {
  const typeMap: Record<string, string> = {
    '紧急': 'danger',
    '高': 'warning',
    '中': 'primary',
    '低': 'info'
  }
  return typeMap[priority] || ''
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 获取客户类型
const loadCustomerTypes = async () => {
  try {
    const types = await customerApi.getCustomerTypes()
    customerTypes.value = types
  } catch (error) {
    console.error('获取客户类型失败', error)
    // 使用默认值
    customerTypes.value = [
      { code: 'U8', name: 'U8' },
      { code: 'BATTERY', name: '电池箔' },
      { code: 'COPPER_ALUMINUM', name: '铜铝复合' },
      { code: 'PURE_ALUMINUM', name: '纯铝' },
      { code: 'RECYCLED_ALUMINUM', name: '再生铝' }
    ]
  }
}

// 加载客户详情
const loadCustomerDetail = async () => {
  if (!props.customerId) return
  
  loading.value = true
  try {
    customer.value = await customerStore.getCustomerById(props.customerId)
    
    // 模拟加载相关项目
    relatedProjects.value = Array(Math.floor(Math.random() * 3)).fill(0).map((_, index) => ({
      id: `project-${index + 1}`,
      projectCode: `P${String(index + 1).padStart(5, '0')}`,
      projectName: `项目${index + 1}`,
      responsiblePerson: `负责人${index + 1}`,
      startTime: new Date(Date.now() - Math.random() * 10000000000).toISOString(),
      endTime: new Date(Date.now() + Math.random() * 10000000000).toISOString(),
      status: ['pre-sales', 'not-started', 'in-progress', 'completed'][Math.floor(Math.random() * 4)]
    }))
    
    // 模拟加载相关工单
    relatedTickets.value = Array(Math.floor(Math.random() * 5)).fill(0).map((_, index) => ({
      id: `ticket-${index + 1}`,
      ticketNo: `T${customer.value?.customerCode}-${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(new Date().getDate()).padStart(2, '0')}-${String(index + 1).padStart(4, '0')}`,
      title: `工单标题${index + 1}`,
      ticketType: Math.random() > 0.5 ? 'Bug' : '需求',
      createTime: new Date(Date.now() - Math.random() * 5000000000).toISOString(),
      status: ['draft', 'submitted', 'confirmed', 'verified', 'pending', 'processing', 'closed'][Math.floor(Math.random() * 7)],
      priority: ['紧急', '高', '中', '低'][Math.floor(Math.random() * 4)]
    }))
  } catch (error) {
    console.error('加载客户详情失败', error)
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadCustomerTypes()
  loadCustomerDetail()
})
</script>

<style scoped>
.customer-detail {
  padding: 20px;
}

.section-title {
  margin: 20px 0 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.section-title h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}
</style>